<?php


class CustomHttpRequest_RequestFailedException extends Exception {
}

class CustomHttpRequest_RequestMethodUnusableException extends Exception {
}


class CustomHttpRequest {
    protected $_urlData;
    protected $_requestUserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204";

    private function _toArray( &$model ) {
        if( is_array($model) ) {
            return $model;
        } elseif( is_object($model) ) {
            if( $model instanceof ArrayAccess ) {
                return $data;
            } else if( is_callable(array($model,'toArrayCopy')) ) {
                    $data = $model->toArray();
                    return $data;
                }
        } elseif( is_null($model) ) {
            $data = array();
            return $data;
        } elseif( !is_resource($model) ) {
            $data = array($model);
            return $data;
        }
        
    }

    public function __construct( $urlData ) {
        $urlData['host'] = preg_replace('@^http://@','',$urlData['host']);
        $this->_urlData = $urlData;
    }

    protected function _getUrlFromData( $urlData ) {
        $urlData = $this->_toArray($urlData);
        $host = $urlData['host'];
        $target = $urlData['target'];
        $queryString = $urlData['query_string'];
        $url = 'http://'.$host.'/'.$target."?".$queryString;
        return $url;
    }

    protected function _makeCurlRequest( $urlData ) {
        if( !function_exists("curl_init") ) {
            throw new CustomHttpRequest_RequestMethodUnusableException('Function "curl_init" not exists');
        }
        $url = $this->_getUrlFromData($urlData);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->_requestUserAgent);
        if (!($contents = trim(@curl_exec($ch)))) {
            throw new CustomHttpRequest_RequestFailedException('Curl exec failed');
        }
        curl_close ($ch);
        return $contents;
    }

    protected function _makeFsockopenRequest( $urlData ) {
        if (!($socket = @fsockopen($host, "80", $errno, $errstr, 30))) {
            throw new CustomHttpRequest_RequestMethodUnusableException('Fsockopen failed with "'.$errstr.' ('.$errno.')" error');
        }
        $urlData = $this->_toArray($urlData);
        $host = $urlData['host'];
        $target = $urlData['target'];
        $queryString = $urlData['query_string'];

        $request = "GET $target?$queryString HTTP/1.1
Host: $host
User-Agent: $this->_requestUserAgent
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7
Cache-Control: max-age=0";
        var_dump($request);
        stream_set_timeout ( $socket,10);
        fwrite( $socket, $request );
        $ret = '';
        while (!feof($socket)) {
            $ret .= fread($socket,4096);
        }
        fclose($socket);
        $contents = trim(substr($ret,strpos($ret,"\r\n\r\n") + 4));
        return $contents;
    }

    protected function _makeFileGetContentsRequest( $urlData ) {
        $url = $this->_getUrlFromData($urlData);
        $contents = @file_get_contents($url);
        if( $contents === false ) {
            $error = error_get_last();
            $errstr = $error['message'];
            $errstr = Text::stripTags($errstr);
            throw new CustomHttpRequest_RequestFailedException('Request sent with function "file_get_contents" failed: '.$errstr);
        }
        $contents = trim($contents);
        return $contents;
    }

    protected function _makeGetRequest( $urlData ) {
        $methods = array(
            'Curl',
            'Fsockopen',
            'FileGetContents',
        );
        foreach( $methods as $name ) {
            $content = null;
            try {
                $content = call_user_func(array($this,'_make'.$name.'Request'),$urlData);
            } catch( CustomHttpRequest_RequestMethodUnusableException $e ) {
            // skipping, logging maybe
            }
            if( is_string($content) ) {
                break;
            }
        }
        return $content;
    }

    public function getContent() {
        return $this->_makeGetRequest($this->_urlData);
    }
}